import 'dart:math';
import 'dart:ui';

import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_overlay_loader/flutter_overlay_loader.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:loading_more_list/loading_more_list.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh_notification/pull_to_refresh_notification.dart';

import 'package:qianyi/controller/homeTabController.dart';
import 'package:qianyi/entity/home/video_list_entity.dart';
import 'package:qianyi/state/token.dart';
import 'package:qianyi/utils/throttle.dart';

import '../../../../controller/imageDetailVideoController.dart';
import '../../../../entity/home/trendVo.dart';
import '../../../../network/http_config.dart';
import '../../../../network/http_manager.dart';
import '../../../../ui/watefall/common/data/tu_chong_repository.dart';
import '../../../../ui/watefall/common/widget/push_to_refresh_header.dart';
import '../../../../ui/widget/custom_refresh.dart';
import '../../../../view_model/detail/TrendViewUserPage.dart';
import '../../../../view_model/mine/trend_view_user_model.dart';
import '../../../../wcao/ui/theme.dart';


class TrendViewUserPage extends StatefulWidget {
  const TrendViewUserPage({Key? key}) : super(key: key);

  @override
  _PageViewMineState createState() => _PageViewMineState();
}

class _PageViewMineState extends State<TrendViewUserPage> with AutomaticKeepAliveClientMixin<TrendViewUserPage> ,SingleTickerProviderStateMixin{
  TokenController tokenController = Get.find();
  ImageDetailVideoController imageDetailVideoController = Get.find();
  Widget buildWaterfallFlowItem1(BuildContext c, TrendEntity item, int index,
      {bool konwSized = true}) {
    const double fontSize = 12.0;

    TrendEntity trendEntity = item;

    return GestureDetector(
      onTap: () async {

        HudUtil.showBeautiful(context);
        String uid = await tokenController.getUid();
        Map<String,dynamic> params = {
          "mid":trendEntity.mid,
          "uid": uid
        };
        HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
        imageDetailVideoController.imageDetailId.value = trendEntity.mid!;
        await imageDetailVideoController.getImageVideoDetail();
        HudUtil.dismiss();
        Get.toNamed("/ui/home/imageVideoDetail");

      },
      child: Card(
        margin: EdgeInsets.all(1.5),

        child: ClipRRect(
          borderRadius: BorderRadius.circular(4.0),
          child:  Column(
            children: [
              FancyShimmerImage(
                height: getRandomHeight1(index),
                imageUrl: trendEntity.cover!,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [

                  Flexible(

                    child: Text(
                      trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                      overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                    ),

                  ),
                  Row(
                    children: [
                      Icon(
                        CupertinoIcons.heart,size: 14,
                        color: Colors.grey,),
                      Text(trendEntity.agreeCount as String)
                    ],
                  )



                ],
              )

              ,


            ],
          ),
        ),
      ),
    );
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    // tokenController.getUserInfo();
  }
  TrendViewUserRepository listSourceRepository = TrendViewUserRepository();
  DateTime? dateTimeNow;

  double get maxDragOffset => 90;
  Future<bool> onRefresh() {
    return listSourceRepository.refresh().whenComplete(() {
      dateTimeNow = DateTime.now();
    });
  }
  @override
  Widget build(BuildContext context) {
    super.build(context); // 重要：调用super.build(context)以保持状态
    return PullToRefreshNotification(
      pullBackOnRefresh: false,
      maxDragOffset: maxDragOffset,
      armedDragUpCancel: false,
      onRefresh: onRefresh,
      child: LoadingMoreCustomScrollView(
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: PullToRefreshContainer(
                    (PullToRefreshScrollNotificationInfo? info) {
                  return PullToRefreshHeader(info, dateTimeNow);
                }),
          ),
          LoadingMoreSliverList<TrendEntity>(
            SliverListConfig<TrendEntity>(
              extendedListDelegate:
              const SliverWaterfallFlowDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 300,
                crossAxisSpacing: 0,
                mainAxisSpacing: 1,
              ),
              itemBuilder: buildWaterfallFlowItem1,
              sourceList: listSourceRepository,
              padding: const EdgeInsets.all(1.0),
              lastChildLayoutType: LastChildLayoutType.foot,
            ),
          )
        ],
      ),
    );
    //   ChangeNotifierProvider(
    //     create: (BuildContext context) => TrendViewUserModel(),
    //     child: Consumer<TrendViewUserModel>(
    //         builder: (context, viewModel, child) {
    //           ;
    //           return CustomRefresh(
    //              // physics: NeverScrollableScrollPhysics(),
    //
    //               isMaterialHeader:true,
    //               controller: viewModel.refreshController,
    //               enablePullUp: true,
    //               onRefresh: () async {
    //                 viewModel.onRefresh();
    //               },
    //               onLoading: () async {
    //                 viewModel.onLoading();
    //               },
    //               child: SingleChildScrollView(
    //                 // physics: NeverScrollableScrollPhysics(),
    //                   child: buildWateFall(viewModel)
    //               )
    //
    //
    //           );
    //         })
    // );


  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  double getRandomHeight1(int index) {
    // 检查imagesHeightMap中是否已经存在对应索引的高度
    if (imagesHeightMap.containsKey(index)) {
      // 如果存在，返回该高度
      return imagesHeightMap[index]!;
    } else {
      // 如果不存在，生成一个新的随机高度并添加到Map中
      double height = Random().nextDouble() * (200 - 80) + 168;
      imagesHeightMap[index] = height;
      return height;
    }
  }
}
Map<int, double> imagesHeightMap = {};

double getRandomHeight1(int index) {
  // 检查imagesHeightMap中是否已经存在对应索引的高度
  if (imagesHeightMap.containsKey(index)) {
    // 如果存在，返回该高度
    return imagesHeightMap[index]!;
  } else {
    // 如果不存在，生成一个新的随机高度并添加到Map中
    double height = Random().nextDouble() * (200 - 80) + 168;
    imagesHeightMap[index] = height;
    return height;
  }
}
double getRandomHeight() {
  // 生成一个随机高度
  double height = Random().nextDouble() * (200 - 80) + 168;
  return   height ;
}
buildWateFall(TrendViewUserModel viewModel) {
  TokenController tokenController = Get.find();

  ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
  return MasonryGridView.count(
    padding: EdgeInsets.all(0),
    // 展示几列
    crossAxisCount: 2,
    // 元素总个数
    itemCount: viewModel.datas.length,
    // 单个子元素
    itemBuilder: (BuildContext context, int index) {
      TrendEntity trendEntity = viewModel.datas[index];
      // var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
      return GestureDetector(
        onTap: () async {

          HudUtil.showBeautiful(context);
          String uid = await tokenController.getUid();
          Map<String,dynamic> params = {
            "mid":trendEntity.mid,
            "uid": uid
          };
          HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
          imageDetailVideoController.imageDetailId.value = trendEntity.mid!;
          await imageDetailVideoController.getImageVideoDetail();
          HudUtil.dismiss();
          Get.toNamed("/ui/home/imageVideoDetail");

        },
        child: Card(
          margin: EdgeInsets.all(1.5),

          child: ClipRRect(
            borderRadius: BorderRadius.circular(4.0),
            child:  Column(
              children: [
                FancyShimmerImage(
                  height: getRandomHeight1(index),
                  imageUrl: trendEntity.cover!,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [

                    Flexible(

                      child: Text(
                        trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                        overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                      ),

                    ),
                    Row(
                      children: [
                        Icon(
                          CupertinoIcons.heart,size: 14,
                          color: Colors.grey,),
                        Text(trendEntity.agreeCount as String)
                      ],
                    )



                  ],
                )

                ,


              ],
            ),
          ),
        ),
      );
    },

    // 纵向元素间距
    mainAxisSpacing: 0,
    // 横向元素间距
    crossAxisSpacing: 0,
    //本身不滚动，让外面的singlescrollview来滚动
    physics:const NeverScrollableScrollPhysics(),
    shrinkWrap: true, //收缩，让元素宽度自适应
  )

  //   WaterfallFlow.builder(
  //   padding: EdgeInsets.all(8.0),
  //   gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
  //     crossAxisCount: 2,
  //
  //     crossAxisSpacing: 5.0,
  //     mainAxisSpacing: 5.0,
  //   ),
  //   itemCount: viewModel.datas.length,
  //   itemBuilder: (BuildContext context, int index) {
  //     TrendEntity trendEntity = viewModel.datas[index];
  //     var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
  //     double height = getRandomHeight();
  //     return Container(
  //       // color: Colors.blue,
  //       height: height,
  //       child: Center(
  //         child: FancyShimmerImage(
  //           height: height-30,
  //           imageUrl: imgsUrl[0],
  //         ),
  //       ),
  //     );
  //   },
  // )
      ;


}
